<?php
/**
 * Created by PhpStorm.
 * User: guokunsheng
 * Date: 2018/6/6
 * Time: 17:38
 */

namespace app\zyhsapi\model;

use app\common\lib\exception\ApiException;
use think\Log as Log;
use XznsTools\cache\zyhs\CacheManageZyhs;

class ZyhsUser extends BaseCacheZyhs
{
    protected $table = 'good_wechat.zyhs_user';

    protected $cacheModel = 'user.user_info';

    /**
     * 更新用户信息
     * @param array $map
     * @param array $data
     * @throws ApiException
     */
    public function updateUserinfo($map = [], $data = [])
    {
        if (!empty($map) && !empty($data))
        {
            try
            {
                $this->where($map)->update($data);

                CacheManageZyhs::getInstance()->setCacheConfig($this->cacheModel, $map['id'])->rmCache();
            }
            catch (\Exception $e)
            {
                Log::write('更新用户信息失败：uid=' . $map['id'] . '-数据:' . json_encode($data, JSON_UNESCAPED_UNICODE), 'error', true);
//                throw new ApiException('您的账号在其他设备登录，请确认是否是自己操作。若要恢复使用，请重新登录。', 200, 403);
            }
        }
    }

    /**
     * 判断用户是否绑定准了号
     * @param array $userinfo
     * @return false|string
     * @throws ApiException
     */
    public function check_uen($userinfo = [])
    {
        // 添加准了号
        if ($userinfo && (!isset($userinfo['uen']) || !$userinfo['uen'] || empty($userinfo['uen'])))
        {
            $uuid = substr(md5(microtime() . $userinfo['id']), 0, 12);

            $uen = ['uen' => $uuid];

            try
            {
                $this->save($uen, ['id' => $userinfo['id']]);

                CacheManageZyhs::getInstance()->setCacheConfig($this->cacheModel, $userinfo['id'])->rmCache();
                return $uuid;
            }
            catch (\Exception $e)
            {
                Log::write('准了号绑定失败：uid=' . $userinfo['id'], 'error');
//                throw new ApiException('准了号绑定失败');
            }
        }
        return false;
    }

    /**
     * 重写数据时获取数据
     * @param $ids
     * @param $type
     * @param $sortType
     * @return array|false|string|void
     */
    public function getInfoByIdsInData($ids, $type, $sortType)
    {
        try
        {
            $field = 'u.id,u.uen,u.token,u.token_expire,u.tel,u.uc_id,u.nickname,u.sex,u.avatar,u.status,u.has_self_recode,u.forbidden,u.regid,u.is_login_record,u.tel_bind_time,u.reg_time,r.id rid,r.name name,r.avatar ravatar';
            $data = $this->alias('u')->join('good_wechat.zyhs_recode r', 'u.id=r.uid and r.isself=1 and r.status=1', 'left')->whereIn('u.id', $ids)->column($field, 'u.id');

            foreach ($data as $uid => $datum)
            {
                if ($datum['rid'])
                {
                    $data[$uid]['nickname'] = $datum['name'];
                    $data[$uid]['avatar'] = $datum['ravatar'];
                } else
                {
                    $data[$uid]['rid'] = 0;
                }
                unset($data[$uid]['name'], $data[$uid]['ravatar']);
            }
        }
        catch (\Exception $e)
        {
            $data = [];
        }

        return $data;
    }

    public function batchGetInfoByIds($cids, $field = [])
    {
        $resData = parent::batchGetInfoByIds($cids, $field);

        return $this->dataInit($resData);
    }

    /**
     * 数据初始化
     * @param array $data
     * @return array
     */
    public function dataInit(array $data)
    {
        foreach ($data as $index => $itemData)
        {
            $data[$index] = arrayKeyData2int($itemData, ['id', 'token_expire', 'sex', 'status', 'has_self_recode', 'forbidden', 'is_login_record', 'tel_bind_time', 'reg_time', 'rid']);
        }

        return $data;
    }

    /**
     * 删除用户缓存
     * @param $uid
     */
    public function removeUserCache($uid)
    {
        CacheManageZyhs::getInstance()->setCacheConfig($this->cacheModel, $uid)->rmCache();
    }
}
